import { useI18n } from '@/hooks/web/useI18n'
import { reactive, ref } from 'vue'
import { CrudSchema } from '@/hooks/web/useCrudSchemas'
import { useValidator } from '@/hooks/web/useValidator'
const { t } = useI18n()
import { ElTag, ElButton, ElIcon } from 'element-plus'
import { Close } from '@element-plus/icons-vue'
import { SelectedItem, useTableDialogStore } from '@/store/modules/tableDialog'
import { useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { ActionButtonsTemplate, TagsObjectType } from '@/api/global/types'
const { required } = useValidator()

interface Option {
  label: string
  value: string | number // 具体取决于你的数据
}

// 通用选项生成函数
const createOptions = (enumObject: { [key: string]: string }): Option[] => {
  return Object.keys(enumObject).map((key) => ({
    label: enumObject[key],
    value: parseInt(key, 10)
  }))
}

export default function (
  actionButtonsTemplate?: ActionButtonsTemplate,
  fieldEnum?: any,
  tableDialogCurdSchema?: CrudSchema[],
  tagsObj?: TagsObjectType,
  tableDialogStoreID?: string,
  customerDialogRef?: any
) {
  const genderOption = reactive(createOptions(fieldEnum?.gender || {}))
  const levelOption = reactive(createOptions(fieldEnum?.level || {}))
  const decisionOption = reactive(createOptions(fieldEnum?.decision || {}))
  const tableDialogStore = useTableDialogStore(tableDialogStoreID)

  const crudSchemas = reactive<CrudSchema[]>([
    {
      field: 'selection',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        type: 'selection'
      }
    },
    {
      field: 'id',
      label: t('customerContact.id'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'cusid',
      label: t('customerContact.cusid'),
      form: {
        component: 'Input',
        formItemProps: {
          rules: [
            {
              validator: (_rule, _value, callback) => {
                if (
                  !tableDialogStore.selectedItems ||
                  tableDialogStore.selectedItems.length === 0
                ) {
                  callback(new Error('该项为必填项'))
                  // callback()
                } else {
                  callback()
                }
              },
              trigger: 'click'
            }
          ]
        },
        componentProps: {
          class: 'invisible-input',
          readonly: true,
          slots: {
            prefix: () => {
              if (tableDialogStore.selectedItems && tableDialogStore.selectedItems.length > 0) {
                return tableDialogStore.selectedItems.map((item: SelectedItem) => (
                  <ElButton
                    size="small"
                    type="success"
                    plain
                    onClick={() => tableDialogStore.removeItem(item.id)}
                  >
                    {item.title}
                    <ElIcon>
                      <Close />
                    </ElIcon>
                  </ElButton>
                ))
              } else {
                // 处理selectedItems为空的情况，可能是返回null或者渲染一些提示信息
                return null
              }
            },
            suffix: () => {
              return (
                <ElButton
                  class="input-button"
                  size="small"
                  type="primary"
                  plain
                  onClick={() => {
                    customerDialogRef.value?.openDialog()
                    customerDialogRef.value?.initialize(
                      tableDialogStore.selectedItems.map((item) => ({ id: item.id }))
                    )
                  }}
                >
                  {t('dealerAssetManagement.select')}
                </ElButton>
              )
            }
          }
        }
      },
      search: {
        component: 'Input',
        formItemProps: {
          rules: [
            {
              validator: (_rule, _value, callback) => {
                if (
                  !tableDialogStore.selectedItems ||
                  tableDialogStore.selectedItems.length === 0
                ) {
                  // callback(new Error('该项为必填项'))
                  callback()
                } else {
                  callback()
                }
              },
              trigger: 'click'
            }
          ]
        },
        componentProps: {
          class: 'invisible-input',
          readonly: true,
          placeholder: t('customer.cusname'),
          slots: {
            prefix: () => {
              if (tableDialogStore.selectedItems && tableDialogStore.selectedItems.length > 0) {
                return tableDialogStore.selectedItems.map((item: SelectedItem) => (
                  <ElButton
                    size="small"
                    type="success"
                    plain
                    onClick={() => tableDialogStore.removeItem(item.id)}
                  >
                    {item.title}
                    <ElIcon>
                      <Close />
                    </ElIcon>
                  </ElButton>
                ))
              }
            },
            append: () => {
              return (
                <ElButton
                  size="small"
                  text
                  type="success"
                  onClick={() => {
                    customerDialogRef.value?.openDialog()
                    customerDialogRef.value?.initialize(
                      tableDialogStore.selectedItems.map((item) => ({ id: item.id }))
                    )
                  }}
                >
                  {t('dealerAssetManagement.select')}
                </ElButton>
              )
            }
          }
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.cusid_value
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '160',
        slots: {
          default: (data: any) => {
            return data.row.cusid_value
          }
        }
      }
    },
    {
      field: 'cname',
      label: t('customerContact.cname'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        formItemProps: {
          rules: [required()]
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '140'
      }
    },
    {
      field: 'gender',
      label: t('customerContact.gender'),
      form: {
        component: 'Select',
        componentProps: {
          options: genderOption
        }
      },
      search: {
        component: 'Select',
        componentProps: {
          options: genderOption,
          style: {
            width: '100%'
          }
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            if (data.gender_value) {
              return (
                <ElTag type={data.gender === 1 ? 'warning' : 'success'}>{data.gender_value}</ElTag>
              )
            } else {
              return null
            }
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '50',
        slots: {
          default: (data: any) => {
            if (data.row.gender_value) {
              return (
                <ElTag type={data.row.gender === 1 ? 'warning' : 'success'}>
                  {data.row.gender_value}
                </ElTag>
              )
            } else {
              return null
            }
          }
        }
      }
    },
    {
      field: 'birthday',
      label: t('customerContact.birthday'),
      search: {
        hidden: true
      },
      form: {
        component: 'DatePicker',
        componentProps: {
          type: 'date',
          valueFormat: 'YYYY-MM-DD'
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '90'
      }
    },
    {
      field: 'phone',
      label: t('customerContact.phone'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        formItemProps: {
          rules: [required()]
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '100'
      }
    },
    {
      field: 'email',
      label: t('customerContact.email'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        formItemProps: {
          rules: [required()]
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '140'
      }
    },
    {
      field: 'qq',
      label: t('customerContact.qq'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input'
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '100'
      }
    },
    {
      field: 'telegram',
      label: t('customerContact.telegram'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input'
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '100'
      }
    },
    {
      field: 'wechat',
      label: t('customerContact.wechat'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input'
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '100'
      }
    },
    {
      field: 'whatsapp',
      label: t('customerContact.whatsapp'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input'
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '100'
      }
    },
    {
      field: 'dingtalk',
      label: t('customerContact.dingtalk'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input'
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '100'
      }
    },
    {
      field: 'country',
      label: t('customerContact.country'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input'
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'address',
      label: t('customerContact.address'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input'
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'department',
      label: t('customerContact.department'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input'
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'position',
      label: t('customerContact.position'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input'
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'level',
      label: t('customerContact.level'),
      search: {
        hidden: true
      },
      form: {
        component: 'Select',
        componentProps: {
          options: levelOption
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            if (data.level_value) {
              return <ElTag type="success">{data.level_value}</ElTag>
            } else {
              return null
            }
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            if (data.row.level_value) {
              return <ElTag type="success">{data.row.level_value}</ElTag>
            } else {
              return null
            }
          }
        }
      }
    },
    {
      field: 'decision',
      label: t('customerContact.decision'),
      search: {
        hidden: true
      },
      form: {
        component: 'Select',
        componentProps: {
          options: decisionOption
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            if (data.decision_value) {
              return <ElTag type="success">{data.decision_value}</ElTag>
            } else {
              return null
            }
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            if (data.row.decision_value) {
              return <ElTag type="success">{data.row.decision_value}</ElTag>
            } else {
              return null
            }
          }
        }
      }
    },
    {
      field: 'tags',
      label: t('customer.tags'),
      search: {
        hidden: true
      },
      form: {
        componentProps: {
          class: 'invisible-input',
          readonly: true,
          slots: {
            prefix: () => {
              return tagsObj?.tagsList.map((item) => (
                <ElButton
                  size="small"
                  type="success"
                  plain
                  onClick={() => tagsObj?.removeTag(item)}
                >
                  {item}
                  <ElIcon>
                    <Close />
                  </ElIcon>
                </ElButton>
              ))
            },
            suffix: () => {
              return (
                <ElButton
                  class="input-button"
                  size="small"
                  type="primary"
                  plain
                  onClick={tagsObj?.handleTagsButtonClick}
                >
                  {t('action.add')}
                </ElButton>
              )
            }
          }
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            if (data.tags) {
              return data.tags?.split(',').map((item) => (
                <ElTag style="margin-left: 5px;" type={'success'}>
                  {item}
                </ElTag>
              ))
            } else {
              return null
            }
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            if (data.row.tags) {
              return data.row.tags?.split(',').map((item) => (
                <ElTag style="margin-left: 5px;" type={'success'}>
                  {item}
                </ElTag>
              ))
            } else {
              return null
            }
          }
        }
      }
    },
    {
      field: 'remark',
      label: t('customerContact.remark'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          type: 'textarea'
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'create_time',
      label: t('customerContact.create_time'),
      search: {
        component: 'DatePicker',
        componentProps: {
          type: 'date',
          valueFormat: 'YYYY-MM-DD'
        }
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'creator',
      label: t('customerContact.creator'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.creator_value
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.creator_value
          }
        }
      }
    },
    {
      field: 'update_time',
      label: t('customerContact.update_time'),
      search: {
        component: 'DatePicker',
        componentProps: {
          type: 'date',
          valueFormat: 'YYYY-MM-DD'
        }
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.update_value
          }
        }
      }
    },
    {
      field: 'updater',
      label: t('customerContact.updater'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        hidden: true
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.updater_value
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'action',
      width: (actionButtonsTemplate?.length || 3) * 60 + 20 + 'px',
      label: t('tableDemo.action'),
      fixed: 'right',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return actionButtonsTemplate?.template(data) ?? null
          }
        }
      }
    }
  ])

  // 客户选择回调
  const handleCustomerSelect = (val: any[]) => {
    if (!val || !val.length) return

    // 更新 store 中的选中项
    const selectedItems = val.map((item) => ({
      id: item.id,
      title: item.cusname
    }))
    tableDialogStore.setCheckedItems(selectedItems)
  }

  return {
    crudSchemas,
    handleCustomerSelect
  }
}
